<template>
    <section class="w-full">
        <p class="page-title">{{this.$route.name}}</p>
        <el-col :span="8" class="b-r h-full">
            <el-tree :data="orgData" node-key="id"
                     :props="defaultProps" ref="tree" @node-click="clickTree" :expand-on-click-node="false">
            </el-tree>
        </el-col>
        <el-col :span="16">
        <div class="wrapper h-full"  >
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.username" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="searchForm.xm" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item label="权限角色">
                    <template>
                        <el-select placeholder="请选择" v-model="searchForm.currentRoleId">
                            <el-option
                                    v-for="item in searchForm.roleForm"
                                    :key="item.roleId"
                                    :label="item.roleName"
                                    :value="item.roleId">
                            </el-option>
                        </el-select>
                    </template>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchUser()">查询</el-button>
                    <el-button @click="reset()">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="tableData"
                    v-auto-height:maxHeight="0"  :height=maxHeight :max-height=maxHeight
            >
                <el-table-column
                        type="index"
                        width="50">
                </el-table-column>
                <el-table-column
                        label="用户名"
                        width="180"
                        prop="userName">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        width="180"
                        prop="realName">
                </el-table-column>
                <el-table-column
                        label="权限角色"
                        width="180"
                        prop="roleName">
                    <template slot-scope="scope">
                        <el-popover trigger="hover" placement="top">
                            <p>角色ID: {{ scope.row.roleId }}</p>
                            <div slot="reference" class="name-wrapper">
                                <el-tag size="medium">{{ scope.row.roleName }}</el-tag>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column>
                    <template slot="header">
                        <el-button type="primary" icon="el-icon-plus" size="small" @click="addUser()">新增用户</el-button>
                    </template>
                    <template slot-scope="scope">
                        <el-button style="margin-left:10px"
                                size="mini" type="primary"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button
                                size="mini" type="primary"
                                icon="el-icon-user"
                                @click="handleRole(scope.row)">角色赋予</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        @size-change="handlePageSizeChange"
                        @current-change="handlePageChange"
                        :current-page="PAGINATION.currentPage"
                        :page-sizes="PAGINATION.pageSizes"
                        :page-size="PAGINATION.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="PAGINATION.total">
                </el-pagination>
            </div>
            <el-dialog :title="diaTitle" :visible.sync="showAddDialog" :close-on-click-modal=false @close="closeUserDialog" width="40%">
                <el-form :model="addForm" status-icon :rules="rules" ref="addForm" label-width="100px" class="demo-dynamic">
                    <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
                        <el-input v-model="addForm.userName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" :label-width="formLabelWidth" prop="userPassword">
                        <el-input v-model="addForm.userPassword" autocomplete="off" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" :label-width="formLabelWidth" prop="userPasswordAgain">
                        <el-input v-model="addForm.userPasswordAgain" autocomplete="off" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="真实姓名" :label-width="formLabelWidth" prop="realName">
                        <el-input v-model="addForm.realName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电子邮件" :label-width="formLabelWidth" prop="email">
                        <el-input v-model="addForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth" prop="tel">
                        <el-input v-model="addForm.tel" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
                        <el-select v-model="addForm.status" placeholder="请选择用户状态" class="w-full">
                            <el-option label="注销" value="2"></el-option>
                            <el-option label="正常" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelUserForm">取 消</el-button>
                    <el-button type="primary" @click="submitForm('addForm')" :loading="addFormLoading">保 存</el-button>
                </div>
            </el-dialog>
            <el-dialog :title="roleDiaTitle" :visible.sync="showGiveRoleDialog" width="40%" @close="closeGiveRoleDialog" :close-on-click-modal=false>
                <el-form :model="roleForm" status-icon ref="roleForm" label-width="100px" class="demo-dynamic" :rules="roleRules">
                    <el-form-item label="角色:" :label-width="formLabelWidth" prop="giveRoleId" >
                        <el-select placeholder="请选择角色" v-model="roleForm.giveRoleId" class="w-full" >
                            <el-option
                                    v-for="item in searchForm.roleForm"
                                    :key="item.roleId"
                                    :label="item.roleName"
                                    :value="item.roleId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelGiveRoleForm">取 消</el-button>
                    <el-button type="primary" @click="submitRoleForm('roleForm')" :loading="giveRoleFormLoading">保 存</el-button>
                </div>
            </el-dialog>
        </div>
    </el-col>
    </section>
</template>



<script>

    import paginationMixin from "../../../mixins/paginationMixin";

    export default {
        name: "userManager",
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.addForm.userPasswordAgain !== '') {
                        this.$refs.addForm.validateField('userPasswordAgain');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.addForm.userPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var CheckTel = (rule, value, callback) => {
                if (!value) {
                    callback();
                }else{
                    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error('请输入正确的手机号'));
                    }
                }
            }
            return {
                maxHeight:'',
                tableHeight:window.innerHeight,
                currentOrgId: '',
                addFormLoading: false,
                giveRoleFormLoading: false,
                currentOrg: {

                },
                orgData: [

                ],
                tableData: [

                ],
                searchForm: {
                    xm: '',
                    username: '',
                    roleForm: [
                        {
                            roleName: '',
                            roleId: ''
                        }
                    ],
                    currentRoleId: ''
                },
                roleDiaTitle: '角色赋予',
                diaTitle: '新增用户',
                showAddDialog: false,
                showGiveRoleDialog: false,
                formLabelWidth: '120px',
                requestMethod: 'post',
                addForm: {
                    userId: '',
                    userName: '',
                    userPassword: '',
                    userPasswordAgain: '',
                    realName: '',
                    email: '',
                    tel: '',
                    status: '1',
                    orgId: ''
                },
                roleForm: {
                    giveRoleId: '',
                    userId: ''
                },
                rules: {
                    userName: [
                        {
                            required: true,
                            message: '请输入用户名',
                            trigger: 'blur'
                        }
                    ],
                    userPassword: [
                        {
                            required: true,
                            message: '请输入密码',
                            trigger: 'blur'
                        },
                        {
                            validator: validatePass,
                            trigger: 'blur'
                        }
                    ],
                    userPasswordAgain: [
                        {
                            required: true,
                            message: '请再次输入密码',
                            trigger: 'blur'
                        },
                        {
                            validator: validatePass2,
                            trigger: 'blur'
                        }
                    ],
                    realName: [
                        {
                            required: true,
                            message: '请输入真实姓名',
                            trigger: 'blur'
                        }
                    ],
                    email: [
                        {
                            type: 'email',
                            message: '请输入正确的邮箱地址',
                            trigger: ['blur', 'change']
                        }
                    ],
                    tel: [
                        {
                            validator: CheckTel,
                            trigger: ['blur', 'change']
                        }
                    ],
                    status: [
                        {
                            required: true,
                            message: '请选择用户状态',
                            trigger: 'blur'
                        }
                    ]
                },
                roleRules: {
                    giveRoleId: [
                        {
                            required: true,
                            message: '请选择角色',
                            trigger: 'blur'
                        }
                    ]
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
            }
        },
        created() {
            this.queryOrgs();
            this.$http({
                url: '/role/roles',
                method: 'get',
                params: {}
            })
            .then((response) => {
                this.searchForm.roleForm = response;
            })
        },
        methods: {
            clickTree(data) {
                this.currentOrgId = data.id;
                this.currentOrg = data;
                this.searchUser();
            },
            queryOrgs() {
                this.$http({
                    url: '/org/orgs',
                    method: 'get',
                    params: {}
                }).then((response) => {
                    this.orgData = response;
                })
            },
            addUser() {
                if(this.currentOrgId==null || this.currentOrgId==''){
                    this.$message({
                        type: 'error',
                        message: '请选择一个机构!'
                    });
                    return;
                }
                this.diaTitle = '在 ['+this.currentOrg.label+'] 机构中新增用户';
                this.addForm.userId = '';
                this.addForm.userName = '';
                this.addForm.userPassword = '';
                this.addForm.userPasswordAgain = '';
                this.addForm.realName = '';
                this.addForm.email = null;
                this.addForm.tel = null;
                this.addForm.status = '1';
                this.addForm.orgId = this.currentOrgId;
                this.showAddDialog = true;
                this.requestMethod = 'post';
            },
            handleEdit(row) {
                this.diaTitle = "编辑用户";
                this.addForm.userId = row.userId;
                this.addForm.userName = row.userName;
                this.addForm.userPassword = row.userPassword;
                this.addForm.userPasswordAgain = row.userPassword;
                this.addForm.realName = row.realName;
                this.addForm.email = row.email;
                this.addForm.tel = row.tel;
                this.addForm.status = row.status;
                this.showAddDialog = true;
                this.addForm.orgId = this.currentOrgId;
                this.requestMethod = 'put';
            },
            addOrEditUser() {
                this.addFormLoading = true;
                this.$http({
                    url: '/user/user',
                    method: this.requestMethod,
                    data: this.$qs.stringify(this.addForm)
                })
                .then(() => {
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.showAddDialog = false;
                    this.addFormLoading = false;
                    this.searchUser();
                })
                .catch(()=>{
                    this.addFormLoading = false;
                });
            },
            handleDelete(row) {
                let userId = row.userId;
                this.$confirm('将删除用户'+row.userName+', 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http({
                        url: '/user/user/'+userId,
                        method: 'delete',
                        params: {}
                    })
                    .then(() => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.searchUser();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            handleRole(row) {
                this.roleForm.giveRoleId = row.roleId;
                this.roleForm.userId  = row.userId;
                this.showGiveRoleDialog = true;
            },
            searchUser() {
                this.$http({
                    url: '/user/user/conditions',
                    method: 'get',
                    params: {
                        orgId: this.currentOrgId,
                        userName: this.searchForm.username,
                        realName: this.searchForm.xm,
                        roleId: this.searchForm.currentRoleId,
                    }
                })
                .then((response) => {
                    console.log(response)
                    this.tableData = response.records;
                    this.PAGINATION.total = response.total;
                    this.PAGINATION.currentPage = response.current;
                })
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.addOrEditUser();
                    } else {
                        return false;
                    }
                });
            },
            submitRoleForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.giveRoleForm();
                    } else {
                        return false;
                    }
                });
            },
            giveRoleForm() {
                this.giveRoleFormLoading = true;
                this.$http({
                    url: '/user-role/userRole',
                    method: 'post',
                    data: this.$qs.stringify({
                        userId: this.roleForm.userId,
                        roleId: this.roleForm.giveRoleId,
                    })
                })
                .then(() => {
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.giveRoleFormLoading = false;
                    this.showGiveRoleDialog = false;
                    this.searchUser();
                })
                .catch(()=>{
                    this.giveRoleFormLoading = false;
                });
            },
            reset(){
                this.searchForm.username = '';
                this.searchForm.xm = '';
                this.searchForm.currentRoleId = '';
            },
            cancelUserForm() {
                this.closeUserDialog();
            },
            closeUserDialog() {
                this.showAddDialog = false;
                this.$refs["addForm"].resetFields();
            },
            cancelGiveRoleForm() {
                this.closeGiveRoleDialog();
            },
            closeGiveRoleDialog() {
                this.showGiveRoleDialog = false;
                this.$refs["roleForm"].resetFields();
            },
            async loadTableData() {
                let result = await this.$http({
                    url: '/user/user/conditions',
                    method: 'get',
                    params: {
                        orgId: this.currentOrgId,
                        userName: this.searchForm.username,
                        realName: this.searchForm.xm,
                        roleId: this.searchForm.currentRoleId,
                    }
                })
                this.tableData = result.records;
                this.PAGINATION.total = result.total;
                this.PAGINATION.currentPage = result.current;
            }
        },
        mixins: [paginationMixin]
    }

</script>

<style scoped>

</style>